/**
 * 动态添加路由
 */

import {
    RoutesDataItem
} from '@/routes'
import homeRoter from '@/routes/homeRoutes';

export const loadView = (view: string) => {
    // 路由懒加载 
    // return ()=> import(`@/views/${view!==''?view:'main.vue'}`)
    // return () => Promise.resolve(require(`@/views/${view!==''?view:'main.vue'}`).default);
    return () => Promise.resolve(require(`@/views/${view}`).default);
};

 
 
export const setItemRouter = (routerList: RoutesDataItem[], dataList: RoutesDataItem[], baseUrl: string) => {
    for (const data of dataList) {
        const path = data.path; //baseUrl + "/" + data.path;
        const route: RoutesDataItem = {
            path: path,
            name: data.name,
            redirect: "",
            meta: {
                icon: "",
                title: data.title,
                auth: true
            }
        };

        if (data.url && data.url !== '') {
            route.component = loadView(data.url);
        }

        if (data.component) {
            route.component = data.component;
        }

        if (data.children && data.children.length > 0) {
            route.redirect = { name: data.children[0].name };
            routerList.push(route);
            setItemRouter(routerList, data.children, path);
        } else {
            routerList.push(route);
        }
    }
};

// 组装动态路由
export const setRouter = (dataList: RoutesDataItem[]) => {
    // 必须为根路由，不能在其他地方生成component，除非在store里面
    // () => import("@/views/Index"),
    // () => Promise.resolve(require(`@/views/${view}`).default)
    // (resolve) => require([`@/views/${view}`], resolve);
    const addRouters: RoutesDataItem = {
        path: "/index",
        name: "index",
        redirect: { name: "home" },
        component: () => import('@/views/main.vue'),//loadView("main.vue"),
        meta: {
            auth: true,
        },
        children: [],
    };
    const lastRouter: RoutesDataItem[] = [
        {
            path: "/:pathMatch(.*)*",
            component: () => import('@/views/404/index.vue'),
            meta: {
                icon: "",
                title: "404",
                auth: false
            },
        },
        {
            path: "/:pathMatch(.*)",
            component: () => import('@/views/404/index.vue'),
            meta: {
                icon: "",
                title: "404",
                auth: false
            },
        }
    ];
    setItemRouter(addRouters.children || [], [...homeRoter, ...dataList], "");
    // setItemRouter(addRouters.children || [], dataList, ""); 
    return [addRouters,...lastRouter];
};
